﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Bussines;
using System.Collections.Generic;

namespace ownx
{
    public partial class wfStock : System.Web.UI.Page
    {
        clStock _clStock;
        TBLObj pBLObj;

        DataSet DS;

        string pTableName = "";
        string pCaption = "";
        string pFilterStr = "";
        string pFileUploadPath = "";
        string pFileDeletedPath = "";
        int pID = -1;
        int pUserID = -1;

        List<object> Edits = new List<object>();        
        List<clFIELDINFO> pFields;
        clFIELDINFO_LIST tFI = null;
        clDB_TABLELista pStockTables;

        #region Page load, datainit

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                lBackURL.Text = Session["DEFAULT_BACK_URL"].ToString();//Request.ServerVariables["HTTP_REFERER"];
                gvStock.SelectedIndex = -1;
                lState.Text = "BROWSE";                
            }
                        
            if (Session["FIELDINFO"] != null)
            {
                try
                {
                    tFI = (clFIELDINFO_LIST)Session["FIELDINFO"];
                }
                catch { }
            }

            if (Session["TABLE"] != null)
            {
                pTableName = (string)Session["TABLE"];
            }
            else
            {
                pTableName = "";
            }

            if (Session["CAPTION"] != null)
            {
                pCaption = Session["CAPTION"].ToString();
            }
            else
            {
                pCaption = pTableName;
            }

            if (Session["FILTER"] != null)
            {
                pFilterStr = Session["FILTER"] as string;                
            }

            pFileUploadPath = Session["DEFAULT_UPLOADED_FILE_PATH"].ToString();
            pFileDeletedPath = Session["DEFAULT_DELETED_FILE_PATH"].ToString();

            //pUserID = pBLObj.USR_ID;
            //if (Session["USR_ID"] != null)
            //{
            //    try
            //    {
            //        pUserID = (int)Session["USR_ID"];
            //    }
            //    catch
            //    {
            //        pUserID = -1;
            //    }
            //}
            //else
            //{
            //    pUserID = -1;
            //}

            pID = -1;
            if (Session["ID"] != null)
            {
                try
                {
                    pID = (int)Session["ID"];
                }
                catch { }
            }

            if (tFI != null && pTableName != "")
            {

                TBLObj blObj = null;
                if (Session["BL"] != null)
                {
                    blObj = (TBLObj)Session["BL"];
                }               
                pBLObj = blObj;
                pUserID = pBLObj.USR_ID;

                _clStock = new clStock(blObj, pTableName);
                pFields = pBLObj.FieldInfo.GetVisibleFields(pTableName);
                DS = _clStock.GetData(pID, pFilterStr);
              
                //ha ez az első meghívás
                if (!(Page.IsPostBack))
                {
                    DataInit();
                    BuildEdits();
                    ShowEdits();                    
                }
                else
                {
                    _clStock = new clStock(blObj, pTableName);
                    ShowEdits();                   
                }
            }
            else
            {
                gvStock.Visible = false;
                pEdits.Visible = false;
                btCancel.Visible = false;
                btOk.Visible = false;
                btUj.Visible = false;
                btDelete.Visible = false;
                lCaption.Visible = false;
                lMessage.Text = "Hiányos paraméterek!";
                if (tFI == null)
                {
                    lMessage.Text += " - Nincs megadva FieldInfo!";
                }
                if (pTableName == "")
                {
                    lMessage.Text += " - Nincs megadva táblanév!";
                }
            }

            if (Session["SHOW_STOCK_BUTTONS"] != null)
            {
                if (Session["SHOW_STOCK_BUTTONS"].ToString() == "1")
                {
                    pStockTables = new clDB_TABLELista(pBLObj);
                    CreateStockButtons();
                }
            }

        }

        private void DataInit()
        {          

            //feltöltöm a detasetet
            DS = _clStock.GetData(pID,pFilterStr);

            gvStock.AutoGenerateColumns = false;

            BoundField BF;
            clFIELDINFO FI;

            if (pID == -1)
            {

                //összerakom a gridet
                if (gvStock.Columns.Count < 2)
                {
                    foreach (DataColumn DC in DS.Tables[0].Columns)
                    {
                        FI = pBLObj.FieldInfo.GetField(pTableName, DC.ColumnName);
                        FI.DataType = DC.DataType;
                        BF = new BoundField();
                        BF.DataField = DC.ColumnName;
                        BF.HeaderText = FI.DisplayText;
                        BF.Visible = FI.IsVisible;
                        if (DC.DataType == typeof(double) || DC.DataType == typeof(float) ||
                            DC.DataType == typeof(decimal))
                        {
                            BF.DataFormatString = "{0:n}";
                        }
                        //if (DC.DataType == typeof(int) || DC.DataType == typeof(Int16) || DC.DataType == typeof(Int32) || DC.DataType == typeof(Int64))
                        //{
                        //    //BF.DataFormatString = "{0}";
                        //}
                        gvStock.Columns.Add(BF);
                    }
                }

                gvStock.DataSource = DS;
                gvStock.DataBind();                
            }

            //elhelyezem a vezérlő gombokat
            btDelete.Visible = pID == -1;
            btUj.Visible = pID == -1;
            pEdits.Style["Left"] = "8px";
            //if (pID == -1)
            //{
            //    btUj.Style["Left"] = "10px";
            //    btUj.Style["Top"] = "80px";
            //    btUj.Style["Width"] = "100px";
            //    btUj.Style["Height"] = "30px";
            //    btDelete.Style["Left"] = "120px";
            //    btDelete.Style["Top"] = "80px";
            //    btDelete.Style["Width"] = "100px";
            //    btDelete.Style["Height"] = "30px";
            //    btOk.Style["Left"] = "230px";
            //    btOk.Style["Top"] = "80px";
            //    btOk.Style["Width"] = "100px";
            //    btOk.Style["Height"] = "30px";
            //    btCancel.Style["Left"] = "340px";
            //    btCancel.Style["Top"] = "80px";
            //    btCancel.Style["Width"] = "100px";
            //    btCancel.Style["Height"] = "30px";
            //    btVissza.Style["Left"] = "450px";
            //    btVissza.Style["Top"] = "80px";
            //    btVissza.Style["Width"] = "100px";
            //    btVissza.Style["Height"] = "30px";

            //    pEdits.Style["Top"] = "385px";
            //}
            //else
            //{
            //    btOk.Style["Left"] = "10px";
            //    btOk.Style["Top"] = "80px";
            //    btOk.Style["Width"] = "100px";
            //    btOk.Style["Height"] = "30px";
            //    btCancel.Style["Left"] = "120px";
            //    btCancel.Style["Top"] = "80px";
            //    btCancel.Style["Width"] = "100px";
            //    btCancel.Style["Height"] = "30px";
            //    pEdits.Style["Top"] = "120px";
            //}

            lUser.Text = pUserID.ToString();
            lCaption.Text = pCaption;           
        }

        //létrehozom az editeket
        void BuildEdits()
        {
            Label L;
            TextBox TB;
            DropDownList DL;
            HyperLink HL;
            FileUpload FU;
            Button B;
            int Y = 5;
            int I = 0;
            int EditType; // 0 - combo, 1 - file upload, 2 - datetime, 3 sima textbox

            foreach (clFIELDINFO Fi in pFields)
            {
                EditType = 3;

                L = new Label();
                L.ID = "L" + I.ToString();
                //L.Style["Position"] = "Relative";
                //L.Style["Float"] = "Left";
                L.Width = 170;
                L.Style["Margin-Left"] = "10px";
                L.Style["Margin-Top"] = "5px";
                L.Text = Fi.DisplayText;
                L.Visible = Fi.DefaultValue == "";
                pEdits.Controls.Add(L);

                if (Fi.IsCombo) { EditType = 0; }
                if (Fi.IsFileUpLoad) { EditType = 1; }
                if (DS.Tables[pTableName].Columns[Fi.FieldName].DataType == typeof(DateTime)) { EditType = 2; }

                switch (EditType)
                {
                    //ha combo a mező
                    case 0:
                        DL = new System.Web.UI.WebControls.DropDownList();
                        DL.ID = "DL_" + Fi.TableName + Fi.FieldName;
                        //DL.Style["Position"] = "Relative";
                        //DL.Style["Float"] = "Left";
                        //DL.Style["Margin-Top"] = "10px";
                        //DL.Style["Margin-Left"] = "10px";
                        //DL.Style["Margin-Right"] = "10px";
                        //DL.Style["Margin-Bottom"] = "10px";
                        DL.CssClass = "other_input";

                        DL.Enabled = !Fi.IsReadOnly;
                        if (Fi.IsReadOnly)
                        {
                            DL.ControlStyle.BackColor = System.Drawing.Color.Gray;
                            DL.ControlStyle.ForeColor = System.Drawing.Color.White;
                        }

                        foreach (clComboListItem LI in Fi.ComboList)
                        {
                            DL.Items.Add(new ListItem(LI.Text, LI.Value));
                        }
                        DL.Visible = Fi.DefaultValue == "";
                        pEdits.Controls.Add(DL);
                        Edits.Add(DL);
                        Fi.Edit = DL;
                        break;

                    //file upload
                    case 1:
                        FU = new System.Web.UI.WebControls.FileUpload();
                        FU.ID = "FU_" + Fi.TableName + Fi.FieldName;
                        //FU.Style["Position"] = "Relative";
                        //FU.Style["Float"] = "Left";
                        //FU.Style["Margin-Top"] = "10px";
                        //FU.Style["Margin-Left"] = "10px";
                        //FU.Style["Margin-Right"] = "10px";
                        //FU.Style["Margin-Bottom"] = "10px";
                        FU.CssClass = "other-input";
                        FU.Enabled = !Fi.IsReadOnly;

                        if (Fi.IsReadOnly)
                        {
                            FU.ControlStyle.BackColor = System.Drawing.Color.Gray;
                            FU.ControlStyle.ForeColor = System.Drawing.Color.White;
                        }

                        FU.Visible = Fi.DefaultValue == "";
                        pEdits.Controls.Add(FU);
                        Edits.Add(FU);
                        Fi.Edit = FU;

                        B = new System.Web.UI.WebControls.Button();
                        B.ID = "B_" + Fi.FieldName;
                        B.CssClass = "other-input";
                        B.Enabled = !Fi.IsReadOnly;
                        B.Text = "Törlés";
                        B.Visible = Fi.DefaultValue == "";

                        pEdits.Controls.Add(B);
                        Edits.Add(B);
                        Fi.Edit3 = B;

                        HL = new System.Web.UI.WebControls.HyperLink();
                        HL.ID = "LB_" + Fi.FieldName;
                        HL.CssClass = "other-input";
                        HL.Enabled = !Fi.IsReadOnly;                        

                        if (Fi.IsReadOnly)
                        {
                            HL.ControlStyle.BackColor = System.Drawing.Color.Gray;
                            HL.ControlStyle.ForeColor = System.Drawing.Color.White;
                        }

                        HL.Visible = Fi.DefaultValue == "";
                        pEdits.Controls.Add(HL);
                        Edits.Add(HL);
                        Fi.Edit2 = HL;                        

                        TB = new System.Web.UI.WebControls.TextBox();
                        TB.ID = "TB_" + Fi.FieldName;                        
                        TB.Text = "";
                        TB.Visible = true;                        
                        Fi.Edit4 = TB;


                        break;

                    //datetime
                    case 2:
                        DL = new DropDownList();
                        DL.ID = "DPY_" + Fi.TableName + Fi.FieldName;
                        //DL.Style["Position"] = "Relative";
                        //DL.Style["Float"] = "Left";
                        //DL.Style["Margin-Top"] = "10px";
                        //DL.Style["Margin-Left"] = "10px";
                        //DL.Style["Margin-Bottom"] = "10px";
                        DL.CssClass = "other-input";
                        DL.Items.Clear();
                        for (int I0 = DateTime.Now.Year - 10; I0 <= DateTime.Now.Year + 10; I0++)
                        {
                            DL.Items.Add(I0.ToString());
                        }
                        DL.Visible = Fi.DefaultValue == "";
                        Edits.Add(DL);
                        Fi.Edit = DL;
                        pEdits.Controls.Add(DL);

                        DL = new DropDownList();
                        DL.ID = "DPM_" + Fi.TableName + Fi.FieldName;
                        //DL.Style["Position"] = "Relative";
                        //DL.Style["Float"] = "Left";
                        //DL.Style["Margin-Top"] = "10px";
                        //DL.Style["Margin-Bottom"] = "10px";
                        DL.CssClass = "other-input";
                        DL.Items.Clear();
                        DL.TextChanged += MonthChange;
                        for (int I1 = 1; I1 <= 12; I1++)
                        {
                            DL.Items.Add(I1.ToString());
                        }
                        DL.Visible = Fi.DefaultValue == "";
                        Edits.Add(DL);
                        Fi.Edit2 = DL;
                        pEdits.Controls.Add(DL);

                        DL = new DropDownList();
                        DL.ID = "DPD_" + Fi.TableName + Fi.FieldName;
                        //DL.Style["Position"] = "Relative";
                        //DL.Style["Float"] = "Left";
                        //DL.Style["Margin-Top"] = "10px";
                        //DL.Style["Margin-Right"] = "10px";
                        //DL.Style["Margin-Bottom"] = "10px";
                        DL.CssClass = "other-input";
                        DL.Items.Clear();
                        for (int I2 = 1; I2 <= 31; I2++)
                        {
                            DL.Items.Add(I2.ToString());
                        }
                        DL.Visible = Fi.DefaultValue == "";
                        Edits.Add(DL);
                        Fi.Edit3 = DL;
                        pEdits.Controls.Add(DL);
                        break;

                    //sima textbox
                    case 3:
                        TB = new System.Web.UI.WebControls.TextBox();
                        TB.ID = "TB_" + Fi.TableName + Fi.FieldName;
                        //TB.Style["Position"] = "Relative";
                        //TB.Style["Float"] = "Left";
                        //TB.Style["Margin-Top"] = "10px";
                        //TB.Style["Margin-Left"] = "10px";
                        //TB.Style["Margin-Right"] = "10px";
                        //TB.Style["Margin-Bottom"] = "10px";
                        TB.CssClass = "editbox";
                        TB.Enabled = !Fi.IsReadOnly;
                        if (Fi.IsReadOnly)
                        {
                            TB.ControlStyle.BackColor = System.Drawing.Color.Gray;
                            TB.ControlStyle.ForeColor = System.Drawing.Color.White;
                        }
                        TB.Visible = Fi.DefaultValue == "";
                        pEdits.Controls.Add(TB);
                        Edits.Add(TB);
                        Fi.Edit = TB;
                        break;
                }

                //ez egy sima panel, azért kell hogy az editek és labelek jó helyre kerüljenek
                //P = new Panel();
                //P.Style["Display"] = "Block";
                //P.Style["Position"] = "Relative";
                //P.Style["Height"] = "35px";
                //P.Style["Width"] = "0px";
                //P.Visible = Fi.DefaultValue == "";
                //pEdits.Controls.Add(P);
                //pEdits.Controls.Add(new LiteralControl("<br />"));


                Fi.lEdit = L;
                Fi.Devider = new LiteralControl("<br />");

                Y += 20;
                I++;
            }
        }

        #endregion

        #region Grid,edit műveletek

        //a gridben lévő radiobutton változása
        protected void rbStockCheckedChanged(object sender, EventArgs e)
        {
            RadioButton rbselected = (RadioButton)sender;

            foreach (GridViewRow dr in gvStock.Rows)
            {
                RadioButton rb = (RadioButton)dr.FindControl("RowSelector");
                if (rb == rbselected)
                {
                    rb.Checked = true;
                    gvStock.SelectedIndex = dr.RowIndex;
                    gvStock_SelectedIndexChanged(gvStock, null);
                }
                else
                {
                    rb.Checked = false;
                }
            }
        }

        //lépegetés a gridben
        protected void gvStock_SelectedIndexChanged(object sender, EventArgs e)
        {
            int I = gvStock.SelectedIndex;
            I = I + gvStock.PageIndex * gvStock.PageSize;
            FillEdits(I);

        }

        //grid page index változás
        protected void gvStock_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvStock.PageIndex = e.NewPageIndex;
        }

        //grid page index változás
        protected void gvStock_PageIndexChanged(object sender, EventArgs e)
        {
            DataInit();
            int I = gvStock.SelectedIndex;
            if (I > gvStock.Rows.Count - 1)
            {
                I = gvStock.Rows.Count - 1;
            }
            try
            {
                GridViewRow dr = gvStock.Rows[I];
                RadioButton rb = (RadioButton)dr.FindControl("RowSelector");
                rbStockCheckedChanged(rb, null);
            }
            catch
            { }


        }

        //megjelenítem az editeket
        void ShowEdits()
        {
            foreach (clFIELDINFO FI in pFields)
            {
                pEdits.Controls.Add((Label)FI.lEdit);
                if (FI.IsCombo)
                {
                    pEdits.Controls.Add((DropDownList)FI.Edit);
                }
                else
                {
                    if (FI.DataType == typeof(DateTime))
                    {                        
                        pEdits.Controls.Add((DropDownList)FI.Edit);
                        pEdits.Controls.Add((DropDownList)FI.Edit2);
                        pEdits.Controls.Add((DropDownList)FI.Edit3);
                    }
                    else
                    {
                        if (FI.IsFileUpLoad)
                        {
                            pEdits.Controls.Add((FileUpload)FI.Edit);
                            pEdits.Controls.Add((HyperLink)FI.Edit2);
                            pEdits.Controls.Add((Button)FI.Edit3);
                            //((HyperLink)FI.Edit2).Click += FileDownloadClick;
                            ((Button)FI.Edit3).Click += FileDeleteClick;     
                        }
                        else
                        {
                            pEdits.Controls.Add((TextBox)FI.Edit);
                        }
                    }
                }
                pEdits.Controls.Add((LiteralControl)FI.Devider);
            }

            if (!IsPostBack)
            {
                if (pID == -1)
                {
                    if (gvStock.Rows.Count > 0 && gvStock.SelectedIndex < gvStock.Rows.Count && !(gvStock.SelectedIndex==-1))
                    {
                        rbStockCheckedChanged((RadioButton)gvStock.Rows[gvStock.SelectedIndex].FindControl("RowSelector"), null);
                    }
                }
                else
                {
                    FillEdits(0);
                }
            }
        }

        void FillEdits(int iRowIndex)
        {
            string Z = "";
            string S = "";
            int I=0;

            if (iRowIndex <= DS.Tables[pTableName].Rows.Count - 1 && lState.Text=="BROWSE")
            {
                if (DS != null && DS.Tables[pTableName].Rows.Count > 0)
                {
                    foreach (clFIELDINFO Fi in pFields)
                    {
                        if (Fi.IsCombo)
                        {
                            ((DropDownList)Fi.Edit).Text = DS.Tables[Fi.TableName].Rows[iRowIndex][Fi.FieldName].ToString();
                        }
                        else
                        {
                            if (Fi.DataType == typeof(DateTime))
                            {
                                ((DropDownList)Fi.Edit).Text = Convert.ToDateTime(DS.Tables[Fi.TableName].Rows[iRowIndex][Fi.FieldName]).Year.ToString();
                                ((DropDownList)Fi.Edit2).Text = Convert.ToDateTime(DS.Tables[Fi.TableName].Rows[iRowIndex][Fi.FieldName]).Month.ToString();
                                ((DropDownList)Fi.Edit3).Text = Convert.ToDateTime(DS.Tables[Fi.TableName].Rows[iRowIndex][Fi.FieldName]).Day.ToString();
                            }

                            if (Fi.DataType == typeof(int))
                            {
                                ((TextBox)Fi.Edit).Text = Convert.ToInt32(DS.Tables[Fi.TableName].Rows[iRowIndex][Fi.FieldName]).ToString();
                            }

                            if (Fi.DataType == typeof(float) || Fi.DataType == typeof(double) || Fi.DataType == typeof(decimal))
                            {
                                ((TextBox)Fi.Edit).Text = Convert.ToDouble(DS.Tables[Fi.TableName].Rows[iRowIndex][Fi.FieldName]).ToString("F2");
                            }

                            if (Fi.DataType == typeof(string))
                            {
                                if (Fi.IsFileUpLoad)
                                {
                                    Z=DS.Tables[Fi.TableName].Rows[iRowIndex][Fi.FieldName].ToString();
                                    ((HyperLink)Fi.Edit2).Visible = (Z != "");

                                    ((FileUpload)Fi.Edit).Visible = Z == "";
                                    ((HyperLink)Fi.Edit2).Visible = Z != "";
                                    ((Button)Fi.Edit3).Visible = Z != "";

                                    ((TextBox)Fi.Edit4).Text = Z;

                                    if (Z != "")
                                    {
                                        I = Z.IndexOf("((()))");
                                        if (I > 0)
                                        {
                                            S = Z.Substring(I + 6, Z.Length-I-6);
                                        }
                                        else
                                        {
                                            S = Z;
                                        }

                                        ((HyperLink)Fi.Edit2).Text = S;
                                        ((HyperLink)Fi.Edit2).NavigateUrl = pFileUploadPath + "/" + Z;
                                    }
                                    else
                                    {
                                        //((LinkButton)Fi.Edit).Text = DS.Tables[Fi.TableName].Rows[iRowIndex][Fi.FieldName].ToString();
                                    }
                                }
                                else
                                {
                                    ((TextBox)Fi.Edit).Text = DS.Tables[Fi.TableName].Rows[iRowIndex][Fi.FieldName].ToString();
                                }
                            }
                        }
                    }

                    Z = pBLObj.FieldInfo.GetIDField(pTableName).FieldName;
                    tbID.Text = DS.Tables[pTableName].Rows[iRowIndex][Z].ToString();
                }
            }
        }

        #endregion

        #region vezérlő gombok eseményei (ok, cancel...)

        protected void btCancel_Click(object sender, EventArgs e)
        {
            if (pID == -1)
            {
                Response.Redirect("wfStock.aspx");
            }
            else
            {
                Response.Redirect(lBackURL.Text);
            }
        }

        protected void bSave_Click(object sender, EventArgs e)
        {
            string Err="";
            if (CheckEdits(ref Err))
            {               
                bool jo = true;
                if (lState.Text == "NEW")
                    jo = Save("NEW", ref Err);
                else
                    jo = Save("EDIT", ref Err);
                if (jo)
                {
                    int si = gvStock.SelectedIndex;

                    DataInit();
                    ShowEdits();
                    FillEdits(0);

                    if (pID == -1)
                    {
                        gvStock.SelectedIndex = si;
                        gvStock_SelectedIndexChanged(sender, e);
                    }
                    lMessage.Text = "";
                }
                else
                {
                    lMessage.Text = "Hiba a mentés közben : " + Err;
                }
            }
            else
            {
                lMessage.Text = Err;
            }
        }

        protected void bDelete_Click(object sender, EventArgs e)
        {
            string Err = "";
            int I = gvStock.SelectedIndex;
            if (I > 0)
            {
                I--;
            }
            else
            {
                if (I == gvStock.Rows.Count - 1)
                {
                    I = 0;
                }
            }
            if (Delete(ref Err))
            {
                DataInit();
                rbStockCheckedChanged(gvStock.Rows[I].FindControl("RowSelector"), null);                
                lMessage.Text = "";
            }
            else
            {
                lMessage.Text = "Hiba a törlés közben : " + Err;
            }
        }

        protected void bUj_Click(object sender, EventArgs e)
        {
            Uj();
        }

        //új rekord
        private void Uj()
        {
            lState.Text = "NEW";

            DS.Tables[pTableName].Rows.Add();

            gvStock.DataSource = DS;
            gvStock.DataBind();

            gvStock.PageIndex = gvStock.PageCount - 1;

            gvStock.SelectedIndex = DS.Tables[pTableName].Rows.Count - 1;

            foreach (clFIELDINFO FI in pFields)
            {
                string DefVal = "";
                if (FI.DefaultValue != "")
                {
                    DefVal = FI.DefaultValue;
                }
                else
                {
                    if (FI.IsCombo)
                    {
                        (FI.Edit as DropDownList).Text = DefVal;
                    }
                    else
                    {
                        if (FI.DataType == typeof(DateTime))
                        {
                            DateTime D = DateTime.Now;
                            try
                            {
                                D = DateTime.Parse(DefVal);
                            }
                            catch
                            {}
                            (FI.Edit as DropDownList).Text = D.Year.ToString();
                            (FI.Edit2 as DropDownList).Text = D.Month.ToString();
                            (FI.Edit3 as DropDownList).Text = D.Day.ToString();
                        }
                        else
                        {
                            if (FI.IsFileUpLoad)
                            {
                                (FI.Edit as FileUpload).Visible = true;
                                (FI.Edit as FileUpload).FileContent.Dispose();
                                (FI.Edit2 as HyperLink).Visible = false;                                
                                (FI.Edit3 as Button).Visible = false;
                                (FI.Edit4 as TextBox).Visible = false;
                            }
                            else
                            {
                                (FI.Edit as TextBox).Text = DefVal;
                            }
                        }
                    }
                }
            }            

            gvStock.DataSource = DS;
            gvStock.DataBind();

            rbStockCheckedChanged(gvStock.Rows[gvStock.Rows.Count - 1].FindControl("RowSelector"), null);

        }

        protected bool Save(string iMod /*EDIT/NEW*/ , ref string oErr)
        {
            clStockData pData = new clStockData();
            List<string> FilesToDelete = new List<string>();

            //összerakom, hogy milyen mezőket kell menteni és azoknak mi az értékük
            pData.IDFieldName = pBLObj.FieldInfo.GetIDField(pTableName).FieldName;

            int I = gvStock.SelectedIndex;
            I = I + gvStock.PageIndex * gvStock.PageSize;

            foreach (clFIELDINFO Fi in pFields)
            {
                if ( (Fi.IsFileUpLoad && (Fi.Edit as FileUpload).Visible)  ||
                    (!Fi.IsFileUpLoad && !Fi.IsReadOnly))
                {
                    pData.FieldNames.Add(Fi.FieldName);

                    if (Fi.IsCombo)
                    {
                        pData.FieldValues.Add((Fi.Edit as DropDownList).Text);
                    }
                    else
                    {
                        if (Fi.DataType == typeof(DateTime))
                        {
                            pData.FieldValues.Add(DateTime.Parse((Fi.Edit as DropDownList).Text + "." + (Fi.Edit2 as DropDownList).Text + "." + (Fi.Edit3 as DropDownList).Text));
                        }
                        else
                        {
                            if (Fi.IsFileUpLoad)
                            {
                                string S;
                                if ((Fi.Edit as FileUpload).Visible)
                                {
                                    if ((Fi.Edit as FileUpload).HasFile)
                                    {
                                        S = DateTime.Now.ToString("yyyyMMdd") + Utilities.GenId(pBLObj.sqlConnection) + "((()))" + (Fi.Edit as FileUpload).FileName;                                                                                    
                                        pData.FieldValues.Add(S);                                
                                        S=HttpRuntime.AppDomainAppPath + pFileUploadPath +@"/" + S;
                                        (Fi.Edit as FileUpload).SaveAs(S);
                                    }
                                    else
                                    {
                                        if (DS.Tables[Fi.TableName].Rows.Count > I)
                                        {
                                            S = DS.Tables[Fi.TableName].Rows[I][Fi.FieldName].ToString();
                                            if (S != "")
                                            {
                                                FilesToDelete.Add(S);
                                            }
                                        }
                                        pData.FieldValues.Add("");
                                    }
                                }
                                else
                                {
                                    S = (Fi.Edit4 as TextBox).Text;
                                    pData.FieldValues.Add(S);
                                }
                            }
                            else
                            {
                                pData.FieldValues.Add((Fi.Edit as TextBox).Text);
                            }
                        }
                    }
                    pData.FieldTypes.Add(DS.Tables[pTableName].Columns[Fi.FieldName].DataType);
                }                
            }

            pData.TableName = pTableName;

            //ha van a táblában created_by és modified_by akkor azt is hozzárakom a mezőlistához
            clFIELDINFO FI;
            if (iMod == "NEW")
            {
                FI = pBLObj.FieldInfo.GetCreatedByField(pTableName);
                if (FI != null)
                {
                    pData.FieldNames.Add(FI.FieldName);
                    pData.FieldValues.Add(lUser.Text);
                    pData.FieldTypes.Add(typeof(Int32));
                }
            }
            FI = pBLObj.FieldInfo.GetModifiedByField(pTableName);
            if (FI != null)
            {
                pData.FieldNames.Add(FI.FieldName);
                pData.FieldValues.Add(lUser.Text);
                pData.FieldTypes.Add(typeof(Int32));
            }

            lState.Text = "BROWSE";
            if (iMod == "EDIT")
            {               
                pData.IDValue = tbID.Text;
                bool Ret = (_clStock.UpdateStock(pData, ref oErr));

                if (Ret && FilesToDelete.Count > 0)
                {
                    foreach (string S1 in FilesToDelete)
                    {
                        System.IO.File.Move(HttpRuntime.AppDomainAppPath + pFileUploadPath + @"\" + S1, HttpRuntime.AppDomainAppPath + pFileDeletedPath + @"\" + S1);
                    }
                }
                return Ret;
            }
            else
                return (_clStock.InsertStock(pData, ref oErr));
        }

        private bool Delete(ref string oErr)
        {
            string IDField = pBLObj.FieldInfo.GetIDField(pTableName).FieldName;
            int id = Convert.ToInt32(DS.Tables[pTableName].Rows[gvStock.SelectedIndex][IDField].ToString());
            return (_clStock.DeleteStock(pTableName, IDField, id, ref oErr));
        }

        #endregion

        private void MonthChange(object Sender, EventArgs E)
        {
            DropDownList DD = null;
            DropDownList DM = Sender as DropDownList;
            DropDownList DY = null;

            foreach (clFIELDINFO FI in pFields)
            {
                if (FI.Edit2 == DM)
                {
                    DY = FI.Edit as DropDownList;
                    DD = FI.Edit3 as DropDownList;
                    break;
                }
            }

            DD.Items.Clear();
            int DMax = 30;

            if (DM.Text == "1" || DM.Text == "3" || DM.Text == "5" || DM.Text == "7" || DM.Text == "8" ||
                DM.Text == "10" || DM.Text == "12")
            {
                DMax = 31;
            }
            if (DM.Text == "2")
            {
                if (Convert.ToInt32(DY.Text) % 400 != 0 && Convert.ToInt32(DY.Text) % 4 == 0)
                {
                    DMax = 29;
                }
                else
                {
                    DMax = 28;
                }
            }
            for (int I2 = 1; I2 <= DMax; I2++)
            {
                DD.Items.Add(I2.ToString());
            }
        }

        protected void btVissza_Click(object sender, EventArgs e)
        {
            Session["FILTER"] = null;
            Response.Redirect(lBackURL.Text);            
        }

        private bool CheckEdits(ref string iErr)
        {
            foreach (clFIELDINFO Fi in pFields)
            {
                if (!Fi.IsCombo && Fi.IsVisible && !Fi.IsReadOnly &&
                    (Fi.DataType == typeof(int) || Fi.DataType == typeof(float) || Fi.DataType == typeof(decimal)))
                {
                    if (Fi.DataType == typeof(int) || Fi.DataType == typeof(Int16) || Fi.DataType == typeof(Int32) || Fi.DataType == typeof(Int64))
                    {
                        try
                        {
                            int I = Convert.ToInt32((Fi.Edit as TextBox).Text);
                        }
                        catch
                        {
                            iErr = "Hibás számérték (" + Fi.DisplayText + " = " + (Fi.Edit as TextBox).Text + ")";
                            return false;
                        }
                    }
                    if (Fi.DataType == typeof(float) || Fi.DataType == typeof(decimal))
                    {
                        try
                        {
                            double F = Convert.ToDouble((Fi.Edit as TextBox).Text);
                        }
                        catch
                        {
                            iErr = "Hibás számérték (" + Fi.DisplayText + " = " + (Fi.Edit as TextBox).Text + ")";
                            return false;
                        }
                    }
                }
            }
            return true;
        }
        
        private void CreateStockButtons()
        {            
            Button B;
            foreach (clDB_TABLE T in pStockTables)
            {
                B = new Button();
                B.Text = T.fDBT_DISPLAYNAME;
                //if (T.fDBT_TABLENAME == pTableName && T.fDBT_FILTER == pFilterStr)
                //{
                //    B.CssClass = "selectedbutton";
                //}
                //else
                //{
                //    B.CssClass = "button";
                //}
                B.CssClass = "button";
                B.Click += btTablesClick;
                pTables.Controls.Add(B);
                pTables.Controls.Add(new LiteralControl("<br /><br />"));
                T.fButton = B;
            }
        }

        private void btTablesClick(object sender, EventArgs e)
        {
            clDB_TABLE T = pStockTables.GetItemByText((sender as Button).Text);
            if (T != null)
            {
                if (T.fDBT_TABLENAME != pTableName || T.fDBT_FILTER != pFilterStr)
                {
                    Session["TABLE"] = T.fDBT_TABLENAME;
                    Session["FILTER"] = T.fDBT_FILTER;
                    Session["CAPTION"] = T.fDBT_DISPLAYNAME;
                    Response.Redirect("wfStock.aspx");
                }
            }
        }

        //private void FileDownloadClick(object sender, EventArgs e)
        //{
        //    string S = (sender as LinkButton).ID;
        //    S = S.Remove(0, 3);

        //    int I = gvStock.SelectedIndex;
        //    I = I + gvStock.PageIndex * gvStock.PageSize;

        //    string Z = DS.Tables[pTableName].Rows[I][S].ToString();
          
        //    Response.Write("<script>window.open('"+pFileUploadPath+@"/"+Z+"','_blank');</script>");            
        //}

        private void FileDeleteClick(object sender, EventArgs e)
        {
            string S = (sender as Button).ID;
            S = S.Remove(0, 2);
            clFIELDINFO FI = tFI.GetField(pTableName, S);
            
            int I = gvStock.SelectedIndex;
            I = I + gvStock.PageIndex * gvStock.PageSize;

            string Z = (FI.Edit4 as TextBox).Text;
            (FI.Edit4 as TextBox).Text = "";
            DS.Tables[pTableName].Rows[I][FI.FieldName] = "";
            (FI.Edit as FileUpload).Visible = true;
            (FI.Edit2 as HyperLink).Visible = false;
            (FI.Edit3 as Button).Visible = false;
        }

        protected void gvStock_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.ID = e.Row.Cells[0].Text;
                e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.gvStock, "Select$" + e.Row.RowIndex);
                //e.Row.Attributes.Add("onclick", "GridView_selectRow(this,'" + e.Row.Cells[0].Text + "')");
                e.Row.Attributes.Add("onmouseover", "GridView_mouseHover(this)");
            }
        }
              
    }
}
